package com.example.smartwaterapi.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.smartwaterapi.common.api.RestApiResponse;
import com.example.smartwaterapi.entity.WaterRecord;
import com.example.smartwaterapi.security.SecurityUser;
import com.example.smartwaterapi.service.UserService;
import com.example.smartwaterapi.service.WaterRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.springframework.http.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 饮水记录控制器
 */
@Tag(name = "饮水记录API", description = "饮水记录管理和统计分析相关接口")
@RestController
@RequestMapping("/api")
public class WaterRecordController {

    private static final Logger log = LoggerFactory.getLogger(WaterRecordController.class);

    @Autowired
    private WaterRecordService waterRecordService;
    
    @Autowired
    private UserService userService;

    /**
     * 添加饮水记录 - /water-record 端点
     */
    @Operation(summary = "添加饮水记录", description = "添加一条新的饮水记录")
    @PostMapping("/water-record")
    public RestApiResponse<Boolean> addRecord(
            @Parameter(description = "饮水记录信息") @RequestBody WaterRecord record,
            Authentication authentication) {
        log.info("收到添加饮水记录请求 [/water-record]: {}", record);
        
        // 如果用户ID为空，从身份验证上下文中获取
        if (record.getUserId() == null && authentication != null) {
            SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
            record.setUserId(securityUser.getUserId());
            log.info("从身份验证上下文中获取用户ID: {}", record.getUserId());
        }
        
        // 添加详细日志，帮助调试
        log.info("处理饮水记录: 用户ID={}, 饮水量={}ml, 饮水类型={}, 记录时间={}", 
                record.getUserId(), record.getAmount(), record.getDrinkType(), record.getRecordTime());
        
        // 添加时区调试信息
        log.info("系统时区信息: 默认时区={}, 当前服务器时间={}, JVM时区={}", 
                java.util.TimeZone.getDefault().getID(),
                java.time.LocalDateTime.now(),
                System.getProperty("user.timezone"));
        
        boolean success = waterRecordService.addRecord(record);
        if (success) {
            return RestApiResponse.created(true);
        }
        return RestApiResponse.error("添加饮水记录失败");
    }
    
    /**
     * 添加饮水记录 - /record 端点 (兼容前端API)
     */
    @Operation(summary = "添加饮水记录", description = "添加一条新的饮水记录 (兼容前端API)")
    @PostMapping("/record")
    public RestApiResponse<Boolean> addWaterRecord(
            @Parameter(description = "饮水记录信息") @RequestBody WaterRecord record,
            Authentication authentication) {
        log.info("收到添加饮水记录请求 [/record]: {}", record);
        
        // 如果用户ID为空，从身份验证上下文中获取
        if (record.getUserId() == null && authentication != null) {
            SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
            record.setUserId(securityUser.getUserId());
            log.info("从身份验证上下文中获取用户ID: {}", record.getUserId());
        }
        
        boolean success = waterRecordService.addRecord(record);
        if (success) {
            return RestApiResponse.created(true);
        }
        return RestApiResponse.error("添加饮水记录失败");
    }

    /**
     * 批量添加饮水记录
     */
    @Operation(summary = "批量添加饮水记录", description = "一次性添加多条饮水记录")
    @PostMapping("/water-record/batch")
    public DeferredResult<RestApiResponse<Boolean>> batchAddRecords(
            @Parameter(description = "饮水记录列表") @RequestBody List<WaterRecord> records,
            Authentication authentication) {
        
        DeferredResult<RestApiResponse<Boolean>> deferredResult = new DeferredResult<>(30000L); // 30秒超时
        
        // 如果用户ID为空且有身份验证信息，为所有记录设置用户ID
        if (authentication != null) {
            SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
            Long userId = securityUser.getUserId();
            
            // 为所有没有用户ID的记录设置ID
            for (WaterRecord record : records) {
                if (record.getUserId() == null) {
                    record.setUserId(userId);
                }
            }
            log.info("批量添加饮水记录：为{}条记录设置用户ID: {}", records.size(), userId);
        }
        
        CompletableFuture.supplyAsync(() -> {
            boolean success = waterRecordService.batchAddRecords(records);
            return success ? RestApiResponse.<Boolean>created(true) : RestApiResponse.<Boolean>error("批量添加饮水记录失败");
        }).whenComplete((result, throwable) -> {
            if (throwable != null) {
                deferredResult.setErrorResult(RestApiResponse.<Boolean>error("处理异常：" + throwable.getMessage()));
            } else {
                deferredResult.setResult(result);
            }
        });
        
        return deferredResult;
    }

    /**
     * 获取用户指定日期的饮水记录
     */
    @Operation(summary = "获取每日饮水记录", description = "获取用户指定日期的所有饮水记录")
    @GetMapping("/water-record/user/{userId}/daily")
    public ResponseEntity<RestApiResponse<List<WaterRecord>>> getUserDailyRecords(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "查询日期", example = "2023-12-01") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        
        List<WaterRecord> records = waterRecordService.getUserDailyRecords(userId, date);
        
        // 设置缓存控制，10分钟有效期
        CacheControl cacheControl = CacheControl.maxAge(10, TimeUnit.MINUTES)
                .noTransform()
                .mustRevalidate();
                
        return ResponseEntity.ok()
                .cacheControl(cacheControl)
                .body(RestApiResponse.ok(records));
    }

    /**
     * 分页获取用户饮水记录
     */
    @Operation(summary = "分页查询饮水记录", description = "分页获取用户所有饮水记录")
    @GetMapping("/water-record/user/{userId}")
    public RestApiResponse<Page<WaterRecord>> getUserRecords(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量(最大100)", example = "10") @RequestParam(defaultValue = "10") Integer pageSize) {
        // 限制最大页大小，避免一次性查询过多数据导致内存压力
        pageSize = Math.min(pageSize, 100);
        Page<WaterRecord> recordPage = waterRecordService.getUserRecords(userId, pageNum, pageSize);
        return RestApiResponse.ok(recordPage);
    }

    /**
     * 获取用户每日饮水总量
     */
    @Operation(summary = "获取每日饮水总量", description = "获取用户指定日期的饮水总量（毫升）")
    @GetMapping("/water-record/user/{userId}/daily-total")
    public ResponseEntity<RestApiResponse<Integer>> getUserDailyTotal(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "查询日期", example = "2023-12-01") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        
        Integer total = waterRecordService.getUserDailyTotal(userId, date);
        
        // 设置缓存控制，5分钟有效期
        CacheControl cacheControl = CacheControl.maxAge(5, TimeUnit.MINUTES)
                .noTransform()
                .mustRevalidate();
                
        return ResponseEntity.ok()
                .cacheControl(cacheControl)
                .body(RestApiResponse.ok(total != null ? total : 0));
    }

    /**
     * 获取用户指定日期范围内每日饮水量
     */
    @Operation(summary = "获取日期范围饮水统计", description = "获取用户指定时间段内每日饮水量统计")
    @GetMapping("/water-record/user/{userId}/daily-totals")
    public ResponseEntity<RestApiResponse<List<Map<String, Object>>>> getUserDailyTotalsByDateRange(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "开始日期", example = "2023-12-01") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期", example = "2023-12-07") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        
        List<Map<String, Object>> totals = waterRecordService.getUserDailyTotalsByDateRange(userId, startDate, endDate);
        
        // 设置缓存控制，30分钟有效期
        CacheControl cacheControl = CacheControl.maxAge(30, TimeUnit.MINUTES)
                .noTransform()
                .mustRevalidate();
                
        return ResponseEntity.ok()
                .cacheControl(cacheControl)
                .body(RestApiResponse.ok(totals));
    }

    /**
     * 获取用户指定日期的饮水类型分布
     */
    @Operation(summary = "获取饮水类型分布", description = "获取用户指定日期各种饮水类型的占比分布")
    @GetMapping("/water-record/user/{userId}/drink-type-distribution")
    public ResponseEntity<RestApiResponse<List<Map<String, Object>>>> getUserDrinkTypeDistribution(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "查询日期", example = "2023-12-01") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        
        List<Map<String, Object>> distribution = waterRecordService.getUserDrinkTypeDistribution(userId, date);
        
        // 设置缓存控制，15分钟有效期
        CacheControl cacheControl = CacheControl.maxAge(15, TimeUnit.MINUTES)
                .noTransform()
                .mustRevalidate();
                
        return ResponseEntity.ok()
                .cacheControl(cacheControl)
                .body(RestApiResponse.ok(distribution));
    }

    /**
     * 获取用户指定日期的每小时饮水量
     */
    @Operation(summary = "获取每小时饮水分布", description = "获取用户指定日期24小时内的饮水量分布")
    @GetMapping("/water-record/user/{userId}/hourly-distribution")
    public ResponseEntity<RestApiResponse<List<Map<String, Object>>>> getUserHourlyDistribution(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "查询日期", example = "2023-12-01") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        
        List<Map<String, Object>> distribution = waterRecordService.getUserHourlyDistribution(userId, date);
        
        // 设置缓存控制，15分钟有效期
        CacheControl cacheControl = CacheControl.maxAge(15, TimeUnit.MINUTES)
                .noTransform()
                .mustRevalidate();
                
        return ResponseEntity.ok()
                .cacheControl(cacheControl)
                .body(RestApiResponse.ok(distribution));
    }

    /**
     * 获取用户饮水目标完成率
     */
    @Operation(summary = "获取饮水目标完成率", description = "计算用户指定日期的饮水目标完成百分比")
    @GetMapping("/water-record/user/{userId}/goal-completion")
    public ResponseEntity<RestApiResponse<Double>> getUserDailyGoalCompletion(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "查询日期", example = "2023-12-01") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        
        double completion = waterRecordService.getUserDailyGoalCompletion(userId, date);
        
        // 设置缓存控制，5分钟有效期
        CacheControl cacheControl = CacheControl.maxAge(5, TimeUnit.MINUTES)
                .noTransform()
                .mustRevalidate();
                
        return ResponseEntity.ok()
                .cacheControl(cacheControl)
                .body(RestApiResponse.ok(completion));
    }

    /**
     * 获取用户连续达标天数
     */
    @Operation(summary = "获取连续达标天数", description = "获取用户连续完成饮水目标的天数")
    @GetMapping("/water-record/user/{userId}/consecutive-goal-days")
    public ResponseEntity<RestApiResponse<Integer>> getUserConsecutiveGoalDays(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        
        int days = waterRecordService.getUserConsecutiveGoalDays(userId);
        
        // 设置缓存控制，1小时有效期
        CacheControl cacheControl = CacheControl.maxAge(1, TimeUnit.HOURS)
                .noTransform()
                .mustRevalidate();
                
        return ResponseEntity.ok()
                .cacheControl(cacheControl)
                .body(RestApiResponse.ok(days));
    }

    /**
     * 获取用户饮水统计概览
     */
    @Operation(summary = "获取饮水统计概览", description = "获取用户指定日期的完整饮水统计数据，包括总量、完成率、连续达标天数、类型分布等")
    @GetMapping("/water-record/user/{userId}/statistics")
    public DeferredResult<RestApiResponse<Map<String, Object>>> getUserStatistics(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "统计日期", example = "2023-12-01") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        
        DeferredResult<RestApiResponse<Map<String, Object>>> deferredResult = new DeferredResult<>(10000L); // 10秒超时
        
        CompletableFuture.supplyAsync(() -> {
            Map<String, Object> statistics = new HashMap<>();

            // 获取当日饮水总量
            Integer dailyTotal = waterRecordService.getUserDailyTotal(userId, date);
            statistics.put("dailyTotal", dailyTotal != null ? dailyTotal : 0);

            // 获取目标完成率
            double goalCompletion = waterRecordService.getUserDailyGoalCompletion(userId, date);
            statistics.put("goalCompletion", goalCompletion);

            // 获取连续达标天数
            int consecutiveDays = waterRecordService.getUserConsecutiveGoalDays(userId);
            statistics.put("consecutiveDays", consecutiveDays);

            // 获取饮水类型分布
            List<Map<String, Object>> drinkTypeDistribution = waterRecordService.getUserDrinkTypeDistribution(userId, date);
            statistics.put("drinkTypeDistribution", drinkTypeDistribution);

            // 获取每小时饮水量分布
            List<Map<String, Object>> hourlyDistribution = waterRecordService.getUserHourlyDistribution(userId, date);
            statistics.put("hourlyDistribution", hourlyDistribution);

            return RestApiResponse.<Map<String, Object>>ok(statistics);
        }).whenComplete((result, throwable) -> {
            if (throwable != null) {
                deferredResult.setErrorResult(RestApiResponse.<Map<String, Object>>error("处理异常：" + throwable.getMessage()));
            } else {
                deferredResult.setResult(result);
            }
        });
        
        return deferredResult;
    }

    /**
     * 获取用户饮水统计概览 - 优化响应大小
     */
    @Operation(summary = "获取饮水统计概览(优化版)", description = "获取用户指定日期的完整饮水统计数据，采用压缩传输")
    @GetMapping("/water-record/user/{userId}/statistics-optimized")
    public ResponseEntity<RestApiResponse<Map<String, Object>>> getUserStatisticsOptimized(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "统计日期", example = "2023-12-01") 
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        
        // 使用并发优化版本获取统计数据
        Map<String, Object> statistics = waterRecordService.getUserWaterStatistics(userId, date);
        
        // 启用压缩和缓存控制
        return ResponseEntity.ok()
                .cacheControl(CacheControl.maxAge(5, TimeUnit.MINUTES).mustRevalidate())
                .header("Content-Encoding", "gzip") // 依靠Spring Boot的自动压缩功能
                .body(RestApiResponse.ok(statistics));
    }

    /**
     * 导出用户饮水记录（流式处理，低内存占用）
     */
    @Operation(summary = "导出饮水记录", description = "导出用户饮水记录为CSV格式")
    @GetMapping("/water-record/user/{userId}/export")
    public ResponseEntity<StreamingResponseBody> exportUserRecords(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "开始日期", example = "2023-01-01") 
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期", example = "2023-12-31") 
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        
        StreamingResponseBody responseBody = outputStream -> {
            try (OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
                 BufferedWriter bufferedWriter = new BufferedWriter(writer)) {
                
                // 写入CSV头
                bufferedWriter.write("日期,时间,饮水量(ml),饮水类型,温度\n");
                
                // 分批处理数据，避免一次性加载全部数据到内存
                int pageNum = 1;
                int pageSize = 100;
                Page<WaterRecord> page;
                
                do {
                    // 分页查询数据
                    page = waterRecordService.getUserRecordsByDateRange(userId, startDate, endDate, pageNum, pageSize);
                    
                    // 逐行写入数据
                    for (WaterRecord record : page.getRecords()) {
                        bufferedWriter.write(String.format("%s,%s,%d,%s,%.1f\n",
                                record.getRecordDate(),
                                record.getRecordTime().toLocalTime(),
                                record.getAmount(),
                                record.getDrinkType(),
                                record.getTemperature() != null ? record.getTemperature() : 0));
                    }
                    
                    // 清空缓冲区，避免内存堆积
                    bufferedWriter.flush();
                    pageNum++;
                    
                } while (page.hasNext());
            } catch (IOException e) {
                throw new RuntimeException("导出饮水记录失败", e);
            }
        };
        
        return ResponseEntity
                .ok()
                .header("Content-Disposition", "attachment; filename=water_records.csv")
                .contentType(MediaType.parseMediaType("text/csv"))
                .body(responseBody);
    }
    
    /**
     * 获取饮水记录列表 - 前端API
     */
    @Operation(summary = "获取饮水记录列表", description = "分页获取当前登录用户的饮水记录")
    @GetMapping("/record/list")
    public RestApiResponse<Map<String, Object>> getRecordList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "100") Integer pageSize,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime,
            Authentication authentication) {
        
        // 从认证对象获取用户ID（防止NumberFormatException）
        Long userId = null;
        try {
            if (authentication.getPrincipal() instanceof SecurityUser) {
                SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
                userId = securityUser.getUserId();
            } else {
                // 直接使用openid从数据库查询用户ID
                userId = userService.getUserIdByOpenid(authentication.getName());
            }
            
            if (userId == null) {
                return RestApiResponse.error("无法获取用户ID");
            }
        } catch (Exception e) {
            return RestApiResponse.error("获取用户ID失败: " + e.getMessage());
        }
        
            Page<WaterRecord> recordPage;
    
    if (startTime != null && endTime != null) {
        try {
            // 处理ISO格式的日期时间字符串（例如：2025-07-17T16:00:00.000Z）
            DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
            
            // 尝试解析完整的日期时间字符串
            LocalDate startDate;
            LocalDate endDate;
            
            try {
                // 先尝试解析为完整日期时间
                LocalDateTime startDateTime = LocalDateTime.parse(startTime, formatter);
                LocalDateTime endDateTime = LocalDateTime.parse(endTime, formatter);
                startDate = startDateTime.toLocalDate();
                endDate = endDateTime.toLocalDate();
            } catch (Exception e) {
                // 如果失败，则尝试只解析日期部分（前10个字符）
                startDate = LocalDate.parse(startTime.substring(0, 10));
                endDate = LocalDate.parse(endTime.substring(0, 10));
            }
            
            recordPage = waterRecordService.getUserRecordsByDateRange(userId, startDate, endDate, pageNum, pageSize);
        } catch (Exception e) {
            return RestApiResponse.error("日期格式不正确: " + e.getMessage());
        }
    } else {
        recordPage = waterRecordService.getUserRecords(userId, pageNum, pageSize);
    }
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", recordPage.getRecords());
        result.put("total", recordPage.getTotal());
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        
        return RestApiResponse.ok(result);
    }
    
    /**
     * 获取饮水统计数据 - 前端API
     */
    @Operation(summary = "获取饮水统计数据", description = "获取当前登录用户的饮水统计数据")
    @GetMapping("/record/statistics")
    public RestApiResponse<Map<String, Object>> getStatistics(
            @Parameter(description = "统计类型:daily,weekly,monthly") @RequestParam(defaultValue = "weekly") String type,
            Authentication authentication) {
        
        // 从认证对象获取用户ID（防止NumberFormatException）
        Long userId = null;
        try {
            if (authentication.getPrincipal() instanceof SecurityUser) {
                SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
                userId = securityUser.getUserId();
            } else {
                // 直接使用openid从数据库查询用户ID
                String openid = authentication.getName();
                userId = userService.getUserIdByOpenid(openid);
                
                if (userId == null) {
                    return RestApiResponse.error("无法获取用户ID，openid: " + openid);
                }
            }
        } catch (Exception e) {
            return RestApiResponse.error("获取用户ID失败: " + e.getMessage());
        }
        
        Map<String, Object> statistics = new HashMap<>();
        
        LocalDate today = LocalDate.now();
        
        // 根据统计类型获取不同的统计数据
        switch (type) {
            case "daily":
                statistics = waterRecordService.getUserWaterStatistics(userId, today);
                break;
            case "monthly":
                // 获取月度统计
                List<Map<String, Object>> monthlyStats = waterRecordService.getUserDailyTotalsByDateRange(
                        userId, today.withDayOfMonth(1), today);
                statistics.put("dailyAmounts", monthlyStats);
                statistics.put("month", today.getMonthValue());
                statistics.put("year", today.getYear());
                
                // 计算月度总量
                int monthlyTotal = monthlyStats.stream()
                    .mapToInt(day -> day.get("amount") != null ? ((Number)day.get("amount")).intValue() : 0)
                    .sum();
                statistics.put("monthlyTotal", monthlyTotal);
                break;
            case "weekly":
            default:
                // 获取周统计 (本周的每一天)
                LocalDate startOfWeek = today.minusDays(today.getDayOfWeek().getValue() - 1);
                List<Map<String, Object>> weeklyStats = waterRecordService.getUserDailyTotalsByDateRange(
                        userId, startOfWeek, today);
                statistics.put("dailyAmounts", weeklyStats);
                statistics.put("startDate", startOfWeek);
                statistics.put("endDate", today);
                
                // 计算周总量
                int weeklyTotal = weeklyStats.stream()
                    .mapToInt(day -> {
                        Object amountObj = day.get("total");
                        if (amountObj instanceof Number) {
                            // 安全转换为int，避免ClassCastException
                            int amount = ((Number) amountObj).intValue();
                            log.debug("日期: {}, 饮水量: {}ml", day.get("record_date"), amount);
                            return amount;
                        }
                        return 0;
                    })
                    .sum();
                log.info("用户ID: {}, 周总量: {}ml, 统计条目: {}", userId, weeklyTotal, weeklyStats.size());
                statistics.put("weeklyTotal", weeklyTotal);
                break;
        }
        
        // 添加汇总数据
        Integer dailyTotal = waterRecordService.getUserDailyTotal(userId, today);
        statistics.put("todayAmount", dailyTotal != null ? dailyTotal : 0);
        double goalCompletion = waterRecordService.getUserDailyGoalCompletion(userId, today);
        statistics.put("todayCompletion", goalCompletion);
        
        // 添加总饮水量统计（所有时间）
        Long allTimeTotal = waterRecordService.getUserAllTimeTotal(userId);
        // 安全处理Long到Integer的转换，避免类型转换异常
        statistics.put("allTimeTotal", allTimeTotal != null ? allTimeTotal.longValue() : 0L);
        
        return RestApiResponse.ok(statistics);
    }
}